import 'package:playtruly/common/services/http.dart';
import 'package:playtruly/common/models/index.dart';
import 'package:playtruly/common/utils/encryption_util.dart';
import 'package:playtruly/common/services/rongcloud_service.dart'; // 🔥 新增：融云服务
import 'package:playtruly/common/api/user_api.dart'; // 🔥 新增：用于获取用户信息
import 'dart:developer' as developer;

/// 好友管理相关API
class FriendApi {
  // 🔥 防重复发送缓存（内存缓存，存储最近发送时间）
  static final Map<String, int> _recentRequestCache = {};
  
  /// 发送好友申请
  /// [senderId] 发送者ID
  /// [receiverId] 接收者ID
  /// [message] 申请消息（可选）
  /// [free] 是否免费（1=免费，0=收费），默认0
  static Future<SendFriendRequestResponse> sendFriendRequest({
    required int senderId,
    required int receiverId,
    String? message,
    int free = 0,
  }) async {
    try {
      developer.log('🔄 =============== 开始发送好友申请（AES加密） ===============');
      developer.log('👤 发送者ID: $senderId');
      developer.log('👤 接收者ID: $receiverId');
      developer.log('💬 申请消息: ${message ?? "无"}');
      developer.log('💰 是否免费: ${free == 1 ? "免费" : "收费"}');

      // 创建请求模型
      final request = SendFriendRequestRequest(
        senderId: senderId,
        receiverId: receiverId,
        message: message,
        free: free,
      );

      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密好友申请数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /friends/send_request/');

      // 发送请求
      final response = await HttpService.to.post(
        '/friends/send_request/',
        data: encryptedPayload,
      );

      developer.log('📨 好友申请响应: $response');

      // 解析响应
      final friendRequestResponse = SendFriendRequestResponse.fromJson(response);

      if (friendRequestResponse.isSuccess) {
        developer.log('✅ 好友申请发送成功');
        developer.log('📝 申请ID: ${friendRequestResponse.requestId}');
        developer.log('💰 积分变化: ${friendRequestResponse.pointsChange ?? 0}');
        
        // 🔥 统一处理：发送融云好友申请推送消息
        await _sendRongCloudFriendRequestPush(receiverId);
        
      } else {
        // 🎯 特殊处理：已经发送过好友申请的情况
        if (friendRequestResponse.message.contains('已经发送过好友申请') || 
            friendRequestResponse.message.contains('请等待对方处理')) {
          developer.log('ℹ️ 好友申请状态: ${friendRequestResponse.message}');
          
          // 🔥 关键修复：即使是重复申请，也要发送融云推送通知对方
          developer.log('🔄 重复申请情况，仍需发送融云推送通知');
          await _sendRongCloudFriendRequestPush(receiverId);
          
        } else {
          developer.log('❌ 好友申请发送失败: ${friendRequestResponse.message}');
        }
      }

      return friendRequestResponse;
    } catch (e) {
      developer.log('💥 发送好友申请异常: $e');
      return SendFriendRequestResponse(
        status: 'error',
        message: '发送好友申请失败: ${e.toString()}',
      );
    }
  }

  /// 获取好友列表
  /// [userId] 用户ID
  /// [groupId] 分组ID（可选）
  /// [status] 好友状态筛选（可选）
  static Future<FriendListResponse> getFriendList({
    required int userId,
    int? groupId,
    String? status,
  }) async {
    try {
      developer.log('🔄 =============== 开始获取好友列表（AES加密） ===============');
      developer.log('👤 用户ID: $userId');
      developer.log('📁 分组ID: ${groupId ?? "全部"}');
      developer.log('📊 状态筛选: ${status ?? "全部"}');

      // 创建请求模型
      final request = FriendListRequest(
        userId: userId,
        groupId: groupId,
        status: status,
      );

      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密好友列表查询数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /friends/list/');

      // 发送请求
      final response = await HttpService.to.post(
        '/friends/list/',
        data: encryptedPayload,
      );

      developer.log('📨 好友列表响应: $response');

      // 解析响应
      final friendListResponse = FriendListResponse.fromJson(response);

      if (friendListResponse.isSuccess) {
        developer.log('✅ 好友列表获取成功');
        developer.log('👥 好友数量: ${friendListResponse.count}');
        for (final friend in friendListResponse.data) {
          developer.log('   👤 ${friend.username} (ID: ${friend.friendId})');
        }
      } else {
        developer.log('❌ 好友列表获取失败: ${friendListResponse.message}');
      }

      return friendListResponse;
    } catch (e) {
      developer.log('💥 获取好友列表异常: $e');
      return FriendListResponse(
        status: 'error',
        count: 0,
        data: [],
        message: '获取好友列表失败: ${e.toString()}',
      );
    }
  }

  /// 获取好友申请列表
  /// [userId] 用户ID
  static Future<FriendRequestListResponse> getFriendRequestList({
    required int userId,
  }) async {
    try {
      developer.log('🔄 =============== 开始获取好友申请列表（AES加密） ===============');
      developer.log('👤 用户ID: $userId');

      // 创建请求模型
      final request = FriendRequestListRequest(userId: userId);

      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密好友申请列表查询数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /friends/request_list/');

      // 发送请求
      final response = await HttpService.to.post(
        '/friends/request_list/',
        data: encryptedPayload,
      );

      developer.log('📨 好友申请列表响应: $response');

      // 解析响应
      final requestListResponse = FriendRequestListResponse.fromJson(response);

      if (requestListResponse.isSuccess) {
        developer.log('✅ 好友申请列表获取成功');
        developer.log('📝 申请数量: ${requestListResponse.count}');
        for (final request in requestListResponse.data) {
          developer.log('   📬 来自用户${request.senderId} - 状态: ${request.status}');
        }
      } else {
        developer.log('❌ 好友申请列表获取失败: ${requestListResponse.message}');
      }

      return requestListResponse;
    } catch (e) {
      developer.log('💥 获取好友申请列表异常: $e');
      return FriendRequestListResponse(
        status: 'error',
        count: 0,
        data: [],
        message: '获取好友申请列表失败: ${e.toString()}',
      );
    }
  }

  /// 处理好友申请（同意/拒绝/忽略）
  /// [requestId] 申请ID
  /// [action] 操作类型 ("accept", "reject", "ignore")
  static Future<HandleFriendRequestResponse> handleFriendRequest({
    required int requestId,
    required String action,
  }) async {
    try {
      developer.log('🔄 =============== 开始处理好友申请（AES加密） ===============');
      developer.log('📝 申请ID: $requestId');
      developer.log('🎯 操作类型: $action');

      // 验证操作类型
      if (!['accept', 'reject', 'ignore'].contains(action)) {
        throw ArgumentError('无效的操作类型: $action');
      }

      // 创建请求模型
      final request = HandleFriendRequestRequest(
        requestId: requestId,
        action: action,
      );

      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密处理好友申请数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /friends/handle_request/');

      // 发送请求
      final response = await HttpService.to.post(
        '/friends/handle_request/',
        data: encryptedPayload,
      );

      developer.log('📨 处理好友申请响应: $response');

      // 解析响应
      final handleResponse = HandleFriendRequestResponse.fromJson(response);

      if (handleResponse.isSuccess) {
        developer.log('✅ 好友申请处理成功');
        developer.log('📝 消息: ${handleResponse.message}');
        if (handleResponse.friendshipId != null) {
          developer.log('🤝 好友关系ID: ${handleResponse.friendshipId}');
        }
      } else {
        developer.log('❌ 好友申请处理失败: ${handleResponse.message}');
      }

      return handleResponse;
    } catch (e) {
      developer.log('💥 处理好友申请异常: $e');
      return HandleFriendRequestResponse(
        status: 'error',
        message: '处理好友申请失败: ${e.toString()}',
      );
    }
  }

  /// 删除好友
  /// [userId] 用户ID
  /// [friendId] 好友ID
  static Future<DeleteFriendResponse> deleteFriend({
    required int userId,
    required int friendId,
  }) async {
    try {
      developer.log('🔄 =============== 开始删除好友（AES加密） ===============');
      developer.log('👤 用户ID: $userId');
      developer.log('👤 好友ID: $friendId');

      // 创建请求模型
      final request = DeleteFriendRequest(
        userId: userId,
        friendId: friendId,
      );

      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密删除好友数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /friends/delete/');

      // 发送请求
      final response = await HttpService.to.post(
        '/friends/delete/',
        data: encryptedPayload,
      );

      developer.log('📨 删除好友响应: $response');

      // 解析响应
      final deleteResponse = DeleteFriendResponse.fromJson(response);

      if (deleteResponse.isSuccess) {
        developer.log('✅ 好友删除成功');
        developer.log('📝 消息: ${deleteResponse.message}');
      } else {
        developer.log('❌ 好友删除失败: ${deleteResponse.message}');
      }

      return deleteResponse;
    } catch (e) {
      developer.log('💥 删除好友异常: $e');
      return DeleteFriendResponse(
        status: 'error',
        message: '删除好友失败: ${e.toString()}',
      );
    }
  }

  /// 查询用户关系
  /// [userId] 用户ID
  /// [targetUserId] 目标用户ID
  static Future<CheckFriendRelationshipResponse> checkFriendRelationship({
    required int userId,
    required int targetUserId,
  }) async {
    try {
      developer.log('🔄 =============== 开始查询用户关系（AES加密） ===============');
      developer.log('👤 用户1 ID (user1_id): $userId');
      developer.log('👤 用户2 ID (user2_id): $targetUserId');

      // 创建请求模型
      final request = CheckFriendRelationshipRequest(
        userId: userId,
        targetUserId: targetUserId,
      );

      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密查询用户关系数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /friends/check_relationship/');

      // 发送请求
      final response = await HttpService.to.post(
        '/friends/check_relationship/',
        data: encryptedPayload,
      );

      developer.log('📨 查询用户关系响应: $response');

      // 解析响应
      final relationshipResponse = CheckFriendRelationshipResponse.fromJson(response);

      if (relationshipResponse.isSuccess) {
        developer.log('✅ 用户关系查询成功');
        if (relationshipResponse.data != null) {
          developer.log('🤝 关系类型: ${relationshipResponse.data!.relationshipType}');
          developer.log('📊 是否为好友: ${relationshipResponse.data!.isFriend ?? false}');
        }
      } else {
        developer.log('❌ 用户关系查询失败: ${relationshipResponse.message}');
      }

      return relationshipResponse;
    } catch (e) {
      developer.log('💥 查询用户关系异常: $e');
      return CheckFriendRelationshipResponse(
        status: 'error',
        message: '查询用户关系失败: ${e.toString()}',
      );
    }
  }

  /// 🔥 统一处理：发送融云好友申请推送消息
  /// [targetUserId] 目标用户ID
  static Future<void> _sendRongCloudFriendRequestPush(int targetUserId) async {
    try {
      developer.log('📤 =============== 统一融云好友申请推送开始 ===============');
      developer.log('🎯 目标用户ID: $targetUserId');
      
      // 🔥 获取目标用户的融云用户ID（通常是手机号）
      String? targetRongCloudUserId;
      
      try {
        developer.log('🔍 尝试通过API获取用户手机号...');
        final userInfoResponse = await UserApi.getUserFilteredContent(
          userId: targetUserId,
          contentType: 'activities', // 随便传一个内容类型，我们只需要用户信息
        );
        if (userInfoResponse.isSuccess && userInfoResponse.user != null) {
          targetRongCloudUserId = userInfoResponse.user!.userPhone;
          developer.log('📱 通过API获取手机号: $targetRongCloudUserId');
        }
      } catch (apiError) {
        developer.log('⚠️ 获取用户信息异常: $apiError');
      }
      
      // 验证融云用户ID
      if (targetRongCloudUserId == null || targetRongCloudUserId.isEmpty) {
        developer.log('❌ 无法获取目标用户的融云用户ID（手机号），跳过融云推送');
        return;
      }
      
      if (targetRongCloudUserId.length != 11 || !targetRongCloudUserId.startsWith(RegExp(r'1[3-9]'))) {
        developer.log('⚠️ 融云用户ID格式异常: $targetRongCloudUserId，跳过融云推送');
        return;
      }
      
      developer.log('✅ 目标融云用户ID验证通过: $targetRongCloudUserId');
      
      // 调用融云服务发送好友申请推送
      final rongCloudSuccess = await RongCloudService.to.sendFriendRequestMessage(targetRongCloudUserId);
      
      if (rongCloudSuccess) {
        developer.log('✅ 统一融云好友申请推送发送成功');
      } else {
        developer.log('❌ 统一融云好友申请推送发送失败');
      }
      
      developer.log('📤 =============== 统一融云好友申请推送结束 ===============');
      
    } catch (e) {
      developer.log('💥 发送融云好友申请推送异常: $e');
      // 融云推送失败不影响主流程，只记录日志
    }
  }
}
